﻿using System;
using Eflong.Structure;
using Eflong.Utility;

namespace Eflong.SocketClient
{
    public class CommWithServer
    {
        public CommWithServer( Client client )
        {
            this.client = client;
        }

        public Client client;

        ~CommWithServer( )
        {
            Dispose( false );
        }

        public void Dispose( )
        {
            Dispose( true );

            GC.SuppressFinalize( this );
        }

        protected virtual void Dispose( bool disposing )
        {
            if ( disposing )
            {
                // 这里是清理"托管资源"的用户代码段
            }

            // 这里是清理"非托管资源"的用户代码段
        }

        public bool Disconnect( )
        {
            client.clientSocket.Disconnect( );
            return true;
        }

        // Used to send request to server;
        public uint SendRequest( Packet packet )
        {
            m_bConnected = client.clientSocket.IsConnected( );
            if ( !m_bConnected ) return 0;

            Packet pPacket = new Packet( packet.GetDataSize( ) , packet.GetpData( ) );

            if ( m_nPacketId == 0x7fffffff ) m_nPacketId = 0;
            m_nPacketId++;
            pPacket.m_dwId = m_nPacketId;

            client.clientThread.AddPacketToSend( pPacket );
            LogWrapper.Logger.Debug( "client.clientThread.AddPacketToSend ..." );
            return m_nPacketId;
        }

        // Used to send broadcast to server;
        public void SendBroadcast( Packet packet )
        {
        }

        // Post notification to owner window
        public bool PostNotification( uint message )
        {
            return false;
        }

        // Set owner windows

        public bool IsConnected( ) { m_bConnected = client.clientSocket.IsConnected( ); return m_bConnected; }

        private bool m_bConnected;

        private uint m_nPacketId; // Id of packet, 0 if broadcasting, big than 0 if requesting;
    }
}